package com.example.helloworld

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*

class TimerRecordAdapter(
    private var records: MutableList<TimerRecord>,
    private val onDeleteClick: (TimerRecord) -> Unit
) : RecyclerView.Adapter<TimerRecordAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val durationText: TextView = view.findViewById(R.id.durationText)
        val dateText: TextView = view.findViewById(R.id.dateText)
        val deleteButton: Button = view.findViewById(R.id.deleteButton)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_timer_record, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val record = records[position]
        
        // 显示计时时长
        val minutes = record.duration.toInt() / 60
        val seconds = record.duration.toInt() % 60
        val millis = ((record.duration - record.duration.toInt()) * 100).toInt()
        holder.durationText.text = String.format("%02d:%02d.%02d", minutes, seconds, millis)
        
        // 显示保存时间
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val saveTimeStr = sdf.format(Date(record.savedTime))
        holder.dateText.text = "保存于：$saveTimeStr"

        holder.deleteButton.setOnClickListener { onDeleteClick(record) }
    }

    override fun getItemCount() = records.size

    fun updateRecords(newRecords: List<TimerRecord>) {
        records.clear()
        records.addAll(newRecords)
        notifyDataSetChanged()
    }
} 